from rest_framework import viewsets, status
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters
from django.utils import timezone
from datetime import timedelta
from django.db.models import Avg, Max, Min, Count
from common.viewsets import BaseModelViewSet
from common.response import APIResponse
from .models import HostMetrics, ProcessInfo, ServiceStatus, AlertRule
from .serializers import (
    HostMetricsSerializer, ProcessInfoSerializer, ServiceStatusSerializer,
    AlertRuleSerializer, HostMetricsStatsSerializer, HostMetricsRealTimeSerializer,
    TopProcessesSerializer, HostStatusSummarySerializer, MonitoringTaskStatusSerializer
)
from cmdb.models import Host


class HostMetricsViewSet(BaseModelViewSet):
    """主机监控指标ViewSet"""
    queryset = HostMetrics.objects.all().order_by('-collected_at')
    serializer_class = HostMetricsSerializer
    filter_backends = [DjangoFilterBackend, filters.OrderingFilter]
    filterset_fields = ['host']
    ordering_fields = ['collected_at']

    @action(detail=False, methods=['get'])
    def realtime(self, request):
        """获取实时监控数据"""
        # 获取最近5分钟的最新数据
        recent_time = timezone.now() - timedelta(minutes=5)

        # 获取每个主机的最新监控数据
        latest_metrics = []
        active_hosts = Host.objects.filter(is_active=True, monitor_enabled=True)

        for host in active_hosts:
            latest_metric = HostMetrics.objects.filter(
                host=host,
                collected_at__gte=recent_time
            ).order_by('-collected_at').first()

            if latest_metric:
                latest_metrics.append(latest_metric)

        serializer = HostMetricsRealTimeSerializer(latest_metrics, many=True)
        return APIResponse.success(serializer.data)

    @action(detail=False, methods=['post'])
    def stats(self, request):
        """获取监控统计数据"""
        serializer = HostMetricsStatsSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        host_id = serializer.validated_data['host_id']
        time_range = serializer.validated_data['time_range']
        metrics = serializer.validated_data['metrics']

        # 计算时间范围
        time_map = {
            '1h': timedelta(hours=1),
            '24h': timedelta(hours=24),
            '7d': timedelta(days=7),
            '30d': timedelta(days=30)
        }
        start_time = timezone.now() - time_map[time_range]

        # 查询数据
        queryset = HostMetrics.objects.filter(
            host_id=host_id,
            collected_at__gte=start_time
        ).order_by('collected_at')

        # 构建响应数据
        result = {
            'host_id': host_id,
            'time_range': time_range,
            'data': []
        }

        for metric in queryset:
            data_point = {
                'timestamp': metric.collected_at,
            }

            for metric_name in metrics:
                if hasattr(metric, metric_name):
                    data_point[metric_name] = getattr(metric, metric_name)

            result['data'].append(data_point)

        return APIResponse.success(result)

    @action(detail=False, methods=['get'])
    def summary(self, request):
        """获取监控摘要"""
        # 获取最近的监控数据
        recent_time = timezone.now() - timedelta(minutes=10)
        recent_metrics = HostMetrics.objects.filter(collected_at__gte=recent_time)

        # 统计各种状态的主机数量
        total_hosts = Host.objects.filter(is_active=True, monitor_enabled=True).count()
        online_hosts = Host.objects.filter(is_active=True, status='online').count()
        offline_hosts = Host.objects.filter(is_active=True, status='offline').count()

        # 计算告警主机数量
        warning_hosts = recent_metrics.filter(
            cpu_usage__gt=80
        ).values('host').distinct().count()

        critical_hosts = recent_metrics.filter(
            cpu_usage__gt=95
        ).values('host').distinct().count()

        summary_data = {
            'total_hosts': total_hosts,
            'online_hosts': online_hosts,
            'offline_hosts': offline_hosts,
            'warning_hosts': warning_hosts,
            'critical_hosts': critical_hosts
        }

        serializer = HostStatusSummarySerializer(summary_data)
        return APIResponse.success(serializer.data)
